import asyncio
import functools
import inspect
from typing import Callable, Optional

def check_security() -> Callable:

    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        async def async_wrapper(*args, **kwargs):
            return await _verify_and_execute(func, args, kwargs)

        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            return _verify_and_execute(func, args, kwargs)

        def _verify_and_execute(func: Callable, args, kwargs):
            # 1. 验证用户是否已认证
            print("访问了authenticate")

            # Get context from kwargs (passed from FastMCP)
            ctx = kwargs.get('ctx')
            if not ctx:
                raise ValueError("Context not provided in function arguments")

            print(" ctx:", ctx)
            request = ctx.get_http_request()
            print(" request.headers:", request.headers)
            # 2. 验证用户是否已认证
            token = request.headers.get("Authorization")
            print(" token:", token)

            # 3. 通过验证，执行原函数
            return func(*args, **kwargs)

        return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper

    return decorator


def authenticate():
    def wrapper(func):
        @functools.wraps(func)
        def _execute(*args, **kwargs):
            ctx = kwargs.get('ctx')
            # if not ctx:
            #     raise ValueError("Context not provided in function arguments")
            #
            # request = ctx.get_http_request()
            print(" 调用了 authenticate")
            return func(self,*args, **kwargs)

        return _execute  # 添加这行返回装饰后的函数
    return wrapper



@authenticate()
def my_private(ctx):
    print("===调用了my_private ===")
    return "Hello, this is a private function!"
if __name__ == "__main__":
    my_private("ctx")